<template>
  <div class="homework-history">
    <div class="layout-container">
      <!-- 侧边栏 -->
      <!-- <div class="sidebar">
        <div class="sidebar-header">
          <h3>习题管理</h3>
        </div>
        <el-menu
          :default-active="activeMenu"
          class="sidebar-menu"
          @select="handleMenuSelect"
        >
          <el-menu-item index="generator">
            <el-icon><Edit /></el-icon>
            <span>习题定制</span>
          </el-menu-item>
          <el-menu-item index="history">
            <el-icon><List /></el-icon>
            <span>历史记录</span>
          </el-menu-item>
          <el-menu-item index="hot">
            <el-icon><Star /></el-icon>
            <span>热点考题</span>
          </el-menu-item>
          <el-menu-item index="mistakes">
            <el-icon><Warning /></el-icon>
            <span>高频错题</span>
          </el-menu-item>
        </el-menu>
      </div> -->

      <!-- 主内容区 -->
      <div class="main-content">
        <el-card class="history-card">
          <template #header>
            <div class="card-header">
              <h2>历史记录</h2>
              <div class="header-controls">
                <span class="page-info">第 {{ currentPage }} 页 / 每页15条 / 共 {{ total }} 条</span>
                <div class="custom-pagination">
                  <el-button 
                    size="small" 
                    :disabled="currentPage <= 1" 
                    @click="jumpToPage(currentPage - 1)"
                  >
                    上一页
                  </el-button>
                  <span class="page-number">{{ currentPage }}</span>
                  <el-button 
                    size="small" 
                    :disabled="currentPage >= Math.ceil(total / 15)" 
                    @click="jumpToPage(currentPage + 1)"
                  >
                    下一页
                  </el-button>
                </div>
                <el-button type="primary" @click="fetchHistoryRecords" :loading="loading">刷新</el-button>
              </div>
            </div>
          </template>
          <div class="history-list" v-loading="loading">
            <div v-if="historyRecords.length === 0 && !loading" class="empty-tip">
              暂无历史记录
            </div>
            <div v-for="(record, index) in historyRecords" 
                 :key="index" 
                 class="history-item"
                 @click="viewHistoryDetail(record)">
              <div class="history-item-header">
                <span class="history-subject">【{{ record.subject }}】{{ formatQuestionType(record.type) }}</span>
                <span class="history-time">{{ record.time || '点击查看详情' }}</span>
              </div>
              <div class="history-content">
                <span v-if="record.content && record.content !== '暂无题目内容'">{{ record.content }}</span>
                <span v-else class="preview-placeholder">
                  <i class="el-icon-document"></i> 点击查看完整习题内容
                </span>
              </div>
              <div class="history-item-footer">
                <el-tag size="small" :type="getDifficultyType(record.difficulty)">
                  {{ getDifficultyLabel(record.difficulty) }}
                </el-tag>
                <span class="topic-tag">{{ record.topic }}</span>
              </div>
            </div>
            <div class="bottom-space"></div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, List, Star, Warning } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { exerciseApi } from '@/api'
import request from '@/utils/request'
import { getHomeworkHistory } from '@/api/homework'

const router = useRouter()
const activeMenu = ref('history')
const historyRecords = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(15)
const total = ref(10)

const handleMenuSelect = (index) => {
  activeMenu.value = index
  if (index === 'generator') {
    router.push('/homework/generator')
  }
}

// 直接跳转到指定页面
const jumpToPage = (page) => {
  console.log('跳转到页面:', page)
  if (page < 1 || page > Math.ceil(total.value / 15)) {
    console.log('页码超出范围，忽略')
    return
  }
  
  if (page === currentPage.value) {
    console.log('当前已是第', page, '页，忽略')
    return
  }
  
  // 更新页码
  currentPage.value = page
  
  // 显示加载中
  loading.value = true
  historyRecords.value = []
  
  // 显示提示
  ElMessage.info({
    message: `正在加载第${page}页数据...`,
    duration: 1000
  })
  
  // 直接调用获取数据
  fetchHistoryRecordsForPage(page)
}

// 为特定页面获取历史记录，绕过缓存
const fetchHistoryRecordsForPage = async (page) => {
  loading.value = true
  
  try {
    // 使用封装好的API函数getHomeworkHistory
    const timestamp = new Date().getTime()
    const response = await getHomeworkHistory({
      teacherId: localStorage.getItem('teacherId'),
      page: page,
      size: 15,
      _t: timestamp
    })
    
    console.log(`获取第${page}页数据响应:`, response)
    
    // 处理响应
    if (response.data && response.data.code === 200) {
      if (Array.isArray(response.data.data)) {
        // 数据是按日期分组的，需要提取所有items
        let allRecords = [];
        let recordIds = [];
        
        // 遍历日期组
        response.data.data.forEach(dateGroup => {
          if (dateGroup.items && Array.isArray(dateGroup.items)) {
            // 收集当前日期组中的所有记录
            dateGroup.items.forEach(item => {
              // 确保题目内容字段存在
              if (!item.content) {
                item.content = "暂无题目内容";
              }
              // 确保题目类型字段存在且正确
              if (!item.questionType) {
                item.questionType = "multiple-choice"; // 设置默认题型
              }
              // 确保主题字段存在
              if (!item.topic) {
                item.topic = "未分类";
              }
              // 确保难度字段存在
              if (!item.difficulty) {
                item.difficulty = "medium"; // 设置默认难度
              }
              
              allRecords.push(item);
              if (item.id) recordIds.push(item.id);
            });
          }
        });
        
        console.log(`第${page}页记录ID: ${recordIds.join(',')}`);
        console.log('处理后的记录: ', allRecords);
        
        // 映射记录到显示格式
        historyRecords.value = allRecords.map(item => {
          // 打印完整的单个记录，帮助调试
          console.log('处理记录的原始数据:', JSON.stringify(item));
          
          // 记录一些调试信息，帮助定位问题
          if (!item.content) {
            console.log('缺少内容字段的记录:', item);
          }
          
          // 尝试从item.type或item.questionType获取题型
          const questionType = item.questionType || item.type || 'multiple-choice';
          
          // 尝试从content字段解析题目内容
          let content = "暂无题目内容";
          if (item.content) {
            content = item.content;
          } else if (typeof item === 'object') {
            // 尝试查找记录中任何可能包含题目内容的字段
            const possibleContentFields = ['content', 'title', 'question', 'description'];
            for (const field of possibleContentFields) {
              if (item[field] && typeof item[field] === 'string') {
                content = item[field];
                break;
              }
            }
          }
          
          return {
            id: item.id,
            subject: item.subject || 'physics',
            topic: item.topic || '未分类',
            content: content,
            difficulty: item.difficulty || 'medium',
            type: questionType,
            answer: item.answer || '暂无答案',
            analysis: item.analysis || '暂无解析',
            // 尝试多种可能的日期字段名
            time: formatDateTime(item.createdTime || item.createTime || item.date || item.time || item.created || item.updated)
          };
        });
        
        // 开始预加载习题详情
        preloadExerciseDetails(historyRecords.value);
        
        // 使用响应中的total或者计算出的记录总数
        total.value = response.data.total || allRecords.length;
      } else {
        console.error('响应数据格式不符合预期 (不是数组):', response.data);
        ElMessage.error('获取数据失败：返回格式异常');
      }
    } else {
      console.error('响应格式不正确:', response);
      ElMessage.error('获取数据失败：格式不正确');
    }
  } catch (error) {
    console.error('获取历史记录失败:', error)
    ElMessage.error('获取历史记录失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 格式化日期时间，增强兼容性
const formatDateTime = (dateTime) => {
  if (!dateTime) {
    return '未知日期';
  }
  
  try {
    // 尝试解析不同格式的日期
    let date;
    
    // 如果是数字时间戳
    if (!isNaN(dateTime)) {
      date = new Date(Number(dateTime));
    } 
    // 如果是ISO格式字符串 (2023-06-01T12:00:00.000Z)
    else if (typeof dateTime === 'string' && dateTime.includes('T')) {
      date = new Date(dateTime);
    } 
    // 如果是其他格式
    else {
      date = new Date(dateTime);
    }
    
    // 验证日期是否有效
    if (isNaN(date.getTime())) {
      console.warn('无效的日期格式:', dateTime);
      return '日期格式错误';
    }
    
    // 格式化为本地日期时间
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch (e) {
    console.error('日期格式化错误:', e, dateTime);
    return '日期解析错误';
  }
}

// 添加全局样式
const globalStyle = document.createElement('style');
globalStyle.textContent = `
.exercise-detail-dialog .el-message-box__content {
  max-height: 70vh;
  overflow-y: auto;
}
.exercise-detail-dialog .el-message-box {
  width: 80%;
  max-width: 600px;
}
.exercise-detail-dialog .el-message-box__message p {
  margin: 0;
  line-height: 1.6;
}
`;
document.head.appendChild(globalStyle);

// 预加载习题详情的缓存
const exerciseDetailCache = ref({});

// 预加载习题详情
const preloadExerciseDetails = async (records) => {
  // 最多预加载前5条记录
  const recordsToPreload = records.slice(0, 5);
  
  // 并行请求所有详情
  const preloadPromises = recordsToPreload.map(async (record) => {
    try {
      // 如果已经有缓存，跳过
      if (exerciseDetailCache.value[record.id]) {
        return;
      }
      
      // 请求详情
      const response = await exerciseApi.getExerciseDetail(record.id);
      if (response && response.data) {
        // 缓存详情
        exerciseDetailCache.value[record.id] = response.data;
        console.log(`预加载习题#${record.id}成功`);
      }
    } catch (error) {
      console.error(`预加载习题#${record.id}失败:`, error);
    }
  });
  
  // 等待所有预加载完成
  await Promise.all(preloadPromises);
};

// 查看历史记录详情
const viewHistoryDetail = async (item) => {
  console.log('显示详情的原始数据:', item);
  
  // 显示加载中提示
  const loadingMessage = ElMessage({
    message: '正在加载详细信息...',
    type: 'info',
    duration: 0
  });
  
  try {
    // 首先检查缓存
    if (exerciseDetailCache.value[item.id]) {
      console.log('使用缓存的习题详情:', exerciseDetailCache.value[item.id]);
      
      // 关闭加载提示
      loadingMessage.close();
      
      // 使用缓存数据
      const detailData = exerciseDetailCache.value[item.id];
      
      // 默认值处理 - 优先使用详情中的数据，如果没有则使用列表中的数据
      const subject = detailData.subject || item.subject || 'physics';
      const topic = detailData.topic || item.topic || '未知知识点';
      const difficulty = detailData.difficulty || item.difficulty || 'medium';
      const type = detailData.questionType || detailData.type || item.type || 'multiple-choice';
      const content = detailData.content || item.content || '暂无题目内容';
      const answer = detailData.answer || item.answer || '暂无';
      const analysis = detailData.analysis || item.analysis || '暂无';
      
      // 获取创建时间
      let time = '未知日期';
      if (detailData.createdTime) {
        time = formatDateTime(detailData.createdTime);
      } else if (item.time) {
        time = item.time;
      }
      
      console.log('使用缓存的详情数据:', {
        subject, topic, difficulty, type, content, answer, analysis, time
      });
      
      showExerciseDetailDialog({
        subject, topic, difficulty, type, content, answer, analysis, time
      });
      return;
    }
    
    // 如果没有缓存，则从后端获取完整的习题详情
    const response = await exerciseApi.getExerciseDetail(item.id);
    console.log('获取到的详细信息:', response);
    
    // 如果成功获取到详情，则使用详情数据，并添加到缓存
    if (response && response.data) {
      // 关闭加载提示
      loadingMessage.close();
      
      // 缓存详情数据
      exerciseDetailCache.value[item.id] = response.data;
      
      // 合并原始数据和详情数据
      const detailData = response.data;
      
      // 默认值处理 - 优先使用详情中的数据，如果没有则使用列表中的数据
      const subject = detailData.subject || item.subject || 'physics';
      const topic = detailData.topic || item.topic || '未知知识点';
      const difficulty = detailData.difficulty || item.difficulty || 'medium';
      const type = detailData.questionType || detailData.type || item.type || 'multiple-choice';
      const content = detailData.content || item.content || '暂无题目内容';
      const answer = detailData.answer || item.answer || '暂无';
      const analysis = detailData.analysis || item.analysis || '暂无';
      
      // 获取创建时间
      let time = '未知日期';
      if (detailData.createdTime) {
        time = formatDateTime(detailData.createdTime);
      } else if (item.time) {
        time = item.time;
      }
      
      console.log('合并后的详情数据:', {
        subject, topic, difficulty, type, content, answer, analysis, time
      });
      
      showExerciseDetailDialog({
        subject, topic, difficulty, type, content, answer, analysis, time
      });
    } else {
      // 如果无法获取详情，则使用原始数据
      loadingMessage.close();
      ElMessage.warning('无法获取完整的习题信息，将显示基本信息');
      
      // 使用列表中的数据
      const subject = item.subject || 'physics';
      const topic = item.topic || '未知知识点';
      const difficulty = item.difficulty || 'medium';
      const type = item.type || 'multiple-choice';
      const content = item.content || '暂无题目内容';
      const answer = item.answer || '暂无';
      const analysis = item.analysis || '暂无';
      const time = item.time || '未知日期';
      
      console.log('使用原始数据:', {
        subject, topic, difficulty, type, content, answer, analysis, time
      });
      
      showExerciseDetailDialog({
        subject, topic, difficulty, type, content, answer, analysis, time
      });
    }
  } catch (error) {
    // 关闭加载提示
    loadingMessage.close();
    
    console.error('获取详情失败:', error);
    ElMessage.error('获取详情失败，将显示基本信息');
    
    // 使用列表中的数据
    const subject = item.subject || 'physics';
    const topic = item.topic || '未知知识点';
    const difficulty = item.difficulty || 'medium';
    const type = item.type || 'multiple-choice';
    const content = item.content || '暂无题目内容';
    const answer = item.answer || '暂无';
    const analysis = item.analysis || '暂无';
    const time = item.time || '未知日期';
    
    showExerciseDetailDialog({
      subject, topic, difficulty, type, content, answer, analysis, time
    });
  }
};

// 显示习题详情对话框
const showExerciseDetailDialog = (data) => {
  const { subject, topic, difficulty, type, content, answer, analysis, time } = data;
  
  // 解析题目内容和选项
  let questionText = content;
  let optionsHtml = '';
  
  if (type === 'multiple-choice' && content && content !== '暂无题目内容') {
    // 尝试提取题干和选项
    const lines = content.split('\n').filter(line => line.trim());
    
    // 第一行通常是题干
    if (lines.length > 0) {
      questionText = lines[0].trim();
      
      // 尝试从剩余行提取选项
      let hasOptions = false;
      optionsHtml = '<strong>选项：</strong><br>';
      
      for (let i = 1; i < lines.length; i++) {
        const line = lines[i].trim();
        // 匹配 A. 内容 或 A：内容 或 A 内容 等格式
        if (line.length > 1 && 'ABCD'.includes(line[0]) && (line[1] === '.' || line[1] === ':' || line[1] === '：' || line[1] === ' ')) {
          hasOptions = true;
          const option = line[0];
          const content = line.substring(line.indexOf(option) + 1).replace(/^[.:\s：]+/, '').trim();
          optionsHtml += `<div style="margin-left:15px;margin-bottom:5px;"><span style="font-weight:bold;margin-right:5px;">${option}.</span> ${content}</div>`;
        }
      }
      
      // 如果没有找到选项，尝试其他解析方法
      if (!hasOptions) {
        // 正则表达式匹配各种选项格式
        const optionRegex = /([A-D])[.:\s：]\s*(.*?)(?=\s*[A-D][.:\s：]|$)/gs;
        let match;
        let fullContent = content;
        
        while ((match = optionRegex.exec(fullContent)) !== null) {
          hasOptions = true;
          optionsHtml += `<div style="margin-left:15px;margin-bottom:5px;"><span style="font-weight:bold;margin-right:5px;">${match[1]}.</span> ${match[2].trim()}</div>`;
        }
      }
      
      // 如果仍然没有找到选项，不显示选项部分
      if (!hasOptions) {
        optionsHtml = '';
      }
    }
  }
  
  // 处理答案显示
  const formattedAnswer = (answer && answer !== '暂无') ? answer : '暂无答案';
  
  // 处理解析显示
  const formattedAnalysis = (analysis && analysis !== '暂无') ? analysis : '暂无解析';
  
  // 添加编辑按钮的样式
  const actionStyle = `
    .exercise-detail-dialog .el-message-box__btns {
      display: flex;
      justify-content: space-between;
      padding-top: 15px;
      border-top: 1px solid #EBEEF5;
    }
    .exercise-detail-dialog .edit-button {
      background-color: #67C23A;
      color: white;
      border-color: #67C23A;
    }
    .exercise-detail-dialog .edit-button:hover {
      background-color: #85ce61;
      border-color: #85ce61;
    }
  `;
  
  const styleElement = document.createElement('style');
  styleElement.textContent = actionStyle;
  document.head.appendChild(styleElement);
  
  ElMessageBox.alert(
    `<div style="font-size:15px;line-height:1.6;">
      <div style="margin-bottom:15px;"><strong>题目：</strong>${questionText}</div>
      ${optionsHtml ? `<div style="margin-bottom:15px;">${optionsHtml}</div>` : ''}
      <div style="margin-bottom:8px;"><strong>科目：</strong>${subject}</div>
      <div style="margin-bottom:8px;"><strong>知识点：</strong>${topic}</div>
      <div style="margin-bottom:8px;"><strong>难度：</strong>${getDifficultyLabel(difficulty)}</div>
      <div style="margin-bottom:8px;"><strong>题型：</strong>${formatQuestionType(type)}</div>
      <div style="margin-bottom:8px;"><strong>答案：</strong>${formattedAnswer}</div>
      <div style="margin-bottom:8px;"><strong>解析：</strong>${formattedAnalysis}</div>
      <div><strong>创建时间：</strong>${time}</div>
    </div>`,
    '习题详情',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '关闭',
      customClass: 'exercise-detail-dialog',
      showCancelButton: false,
      distinguishCancelAndClose: true
    }
  );
};

// 格式化题型
const formatQuestionType = (type) => {
  const typeMap = {
    'multiple-choice': '选择题',
    'fill-blank': '填空题',
    'true-false': '判断题',
    'short-answer': '简答题'
  };
  return typeMap[type] || type;
}

// 获取难度标签颜色类型
const getDifficultyType = (difficulty) => {
  const types = {
    easy: 'success',
    medium: 'warning',
    hard: 'danger'
  }
  return types[difficulty] || 'info'
}

// 获取难度标签文本
const getDifficultyLabel = (difficulty) => {
  const labels = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return labels[difficulty] || '未知'
}

// 获取历史记录（默认获取第一页）
const fetchHistoryRecords = async () => {
  currentPage.value = 1
  fetchHistoryRecordsForPage(1)
}

onMounted(() => {
  // 加载第一页历史记录数据
  fetchHistoryRecords()
})
</script>

<style scoped>
.homework-history {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
  margin-top: 60px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.layout-container {
  display: flex;
  gap: 20px;
  min-height: calc(100vh - 100px);
  margin-top: -120px;
  align-items: flex-start;
  flex: 1;
}

.sidebar {
  width: 240px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 80px;
  height: calc(100vh - 100px);
  overflow-y: auto;
}

.sidebar-header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
  font-weight: 600;
}

.sidebar-menu {
  border-right: none;
}

.main-content {
  flex: 1;
  min-width: 0;
  height: auto;
  overflow-y: visible;
  padding: 20px;
}

.history-card {
  height: auto;
  min-height: calc(100vh - 140px);
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.history-list {
  max-height: calc(100vh - 190px);
  height: auto;
  overflow-y: auto;
  padding: 10px 10px 25px 10px;
  margin-bottom: 20px;
}

.history-item {
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.history-item:hover {
  background-color: #f5f7fa;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.history-item:last-child {
  margin-bottom: 30px; /* 为最后一项增加额外的底部边距 */
}

.history-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.history-subject {
  font-weight: 600;
  color: #303133;
}

.history-time {
  font-size: 12px;
  color: #909399;
}

.history-content {
  font-size: 14px;
  color: #606266;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin-bottom: 8px;
}

.history-item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.topic-tag {
  font-size: 12px;
  color: #909399;
  background-color: #f4f4f5;
  padding: 2px 8px;
  border-radius: 4px;
}

.empty-tip {
  text-align: center;
  padding: 40px 0;
  color: #909399;
  font-size: 14px;
}

/* 添加滚动条样式 */
.history-list::-webkit-scrollbar {
  width: 6px;
}

.history-list::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.history-list::-webkit-scrollbar-track {
  background-color: transparent;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
  font-weight: 600;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 15px;
}

.page-info {
  font-size: 13px;
  color: #606266;
  white-space: nowrap;
}

.custom-pagination {
  display: flex;
  align-items: center;
  gap: 10px;
  background: #f5f7fa;
  padding: 5px 10px;
  border-radius: 4px;
}

.page-number {
  font-size: 14px;
  font-weight: bold;
  color: #409EFF;
  min-width: 24px;
  text-align: center;
}

.bottom-space {
  height: 30px;
  width: 100%;
}

.preview-placeholder {
  color: #909399;
  font-style: italic;
  display: flex;
  align-items: center;
  gap: 5px;
}

.preview-placeholder i {
  font-size: 16px;
  color: #409EFF;
}
</style> 